#include "jwt.h"
void split_string(const char *str, char **part1, char **part2) {
    if (str == NULL || part1 == NULL || part2 == NULL) {
        *part1 = NULL;
        *part2 = NULL;
        return;
    }

    const char *first = strchr(str, '$');
    if (first == NULL) {  
        *part1 = NULL;
        *part2 = NULL;
        return;
    }

    const char *second = strchr(first + 1, '$');
    if (second == NULL) {  
        *part1 = NULL;
        *part2 = NULL;
        return;
    }

    size_t len1 = second - (first + 1);  
    *part1 = (char *)malloc(len1 + 1);   
    strncpy(*part1, first + 1, len1);   
    (*part1)[len1] = '\0';      

    *part2 = strdup(second + 1);  // strdup 会自动分配内存并复制
}
char random_token_char() {
    const char* chars = "wangshengzhong.zuozhoulin/zhengwenyi.guojianquan/zhangyu.liuchunjun";
    return chars[rand() % 68];
}
char* generate_token_salt(char *salt,int salt_size) {
    char random_salt[17];  // 16字节随机盐 + 终止符
                           // 生成16字节随机盐
    for (int i = 0; i < 16; i++) {
        random_salt[i] = random_token_char();
    }
    random_salt[16] = '\0';
    snprintf(salt, salt_size, "%s", random_salt);  // 使用默认rounds
    return salt;
}
int generate_jwt( char *salt,char *user_name,int expire_time,char *jwt_str){
    // 创建 JWT 令牌
    jwt_t *jwt = NULL;
    int ret = jwt_new(&jwt);
    if (ret != 0) {
        fprintf(stderr, "初始化JWT对象失败: %d\n", ret);
        return -1;
    }
    jwt_add_grant(jwt,"user_name",user_name); // 假如用户名属性
    jwt_add_grant_int(jwt, "exp", time(NULL) + expire_time); // 12小时后过期
    ret = jwt_set_alg(jwt, JWT_ALG_HS256, (unsigned char *)salt, strlen(salt));
    if (ret != 0) {
        fprintf(stderr, "设置签名算法失败: %d\n", ret);
        jwt_free(jwt);
        return -1;
    }
    // 生成 JWT 字符串
    char *jwt_s = jwt_encode_str(jwt);
    if (!jwt_s) {
        fprintf(stderr, "编码 JWT 失败\n");
        jwt_free(jwt);
        return -1;
    }
    strcpy(jwt_str,jwt_s);
    jwt_free(jwt);
    return 0;
}
int merge_salt_and_jwt(char *res,char *salt,char *jwt_str){
    strcat(res,"$");
    strcat(res,salt);
    strcat(res,"$");
    strcat(res,jwt_str);
    return 0;
}
int get_jwt(char *all_jwt,char* user_name,int expire_time){
    char salt[100]={0};
    char jwt_str[300]={0};
    generate_token_salt(salt,sizeof(salt));
    int ret=generate_jwt(salt,user_name,expire_time,jwt_str);
    if(!ret){
        merge_salt_and_jwt(all_jwt,salt,jwt_str);
        return 0;
    }else{
        return -1;
    }
}
int valid_jwt(char *jwt_str,char *user_name){
    char *salt= NULL;
    char *token = NULL;

    split_string(jwt_str,&salt,&token);

    if (salt && token) {
        /* printf("拆分结果：\n"); */
        /* printf("子串1：%s\n", salt); */  
        /* printf("子串2：%s\n", token); */
    } else {
        printf("字符串格式错误!\n");
        return -2;
    }
    jwt_t *decoded_jwt = NULL;
    int ret = jwt_decode(&decoded_jwt, token, (unsigned char *)salt, strlen(salt));
    if (ret != 0) {
        fprintf(stderr, "验证 JWT 失败: %d\n", ret);
        return -1;
    } else {
        int exp = jwt_get_grant_int(decoded_jwt, "exp");
        const char *extracted_username = jwt_get_grant(decoded_jwt, "user_name");
        if((time(NULL)<exp)&&strcmp(extracted_username,user_name)==0){
            jwt_free(decoded_jwt);
            return 0;
        }else{
            jwt_free(decoded_jwt);
            return -1;
        }
    }
}

